import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {HttpClient} from '@angular/common/http';
import {NzMessageService} from 'ng-zorro-antd';
import {ActivatedRoute, Router} from '@angular/router';
import {environment} from '../../../../environments/environment';

@Component({
  selector: 'app-detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.scss']
})
export class DetailComponent implements OnInit {
  form: FormGroup;
  id;

  constructor(
    private fb: FormBuilder,
    private http: HttpClient,
    private message: NzMessageService,
    private router: Router,
    private route: ActivatedRoute
  ) {
  }

  ngOnInit(): void {
    this.form = this.fb.group({
      id: [],
      createTime: [],
      updateTime: [],
      deleted: [],
      remark: ['', [Validators.required]],
      host: ['', [Validators.required]],
      port: ['', [Validators.required]],
      username: ['', [Validators.required]],
      password: [],
    });
    this.route.paramMap.subscribe(param => {
      if (param.get('id')) {
        this.id = param.get('id');
        this.http.get(environment.uri + '/machine/' + this.id).subscribe(res => {
          this.form.patchValue(res);
        });
      }
    });
  }


  submitForm(value: any): void {
    for (const key in this.form.controls) {
      if (key) {
        this.form.controls[key].markAsDirty();
        this.form.controls[key].updateValueAndValidity();
      }
    }
    this.http.post(environment.uri + '/machine', value).subscribe(() => {
      if (this.id) {
        this.message.create('success', '修改成功');
      } else {
        this.message.create('success', '创建成功');
      }
      this.router.navigate(['/machine']);
    });
  }

  resetForm(e: MouseEvent): void {
    e.preventDefault();
    this.form.reset();
    for (const key in this.form.controls) {
      if (key) {
        this.form.controls[key].markAsPristine();
        this.form.controls[key].updateValueAndValidity();
      }
    }
  }

}
